<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '我的',
  },
}
</route>

<script lang="ts" setup>
import { BASE_URL } from '@/constants'
import { posterControllerGetQrCode as getSun } from '@/service/app'
import { useUserStore } from '@/store'
import CalendarActivity from '@/components/calendar-activity/calendar-activity.vue'

const userStore = useUserStore()

// 获取屏幕边界到安全区域距离
let safeAreaInsets
let systemInfo

// #ifdef MP-WEIXIN
// 微信小程序使用新的API
systemInfo = uni.getWindowInfo()
safeAreaInsets = systemInfo.safeArea
  ? {
      top: systemInfo.safeArea.top,
      right: systemInfo.windowWidth - systemInfo.safeArea.right,
      bottom: systemInfo.windowHeight - systemInfo.safeArea.bottom,
      left: systemInfo.safeArea.left,
    }
  : null
// #endif

// #ifndef MP-WEIXIN
// 其他平台继续使用uni API
systemInfo = uni.getSystemInfoSync()
safeAreaInsets = systemInfo.safeAreaInsets
// #endif

const userInfo = computed(() => {
  const storeInfo = userStore.userInfo
  return {
    nickName: storeInfo.username || '微信用户', // 用username作为昵称，默认值兜底
    avatarUrl: BASE_URL + storeInfo.avatar || '/static/images/default-avatar.png', // 头像地址，默认图兜底
  }
})

function toOrderList(type: string) {
  uni.navigateTo({
    url: `/pages/order/orderList?type=${type}`,
    success: (res) => {
      res.eventChannel.emit('acceptDataFromOpenerPage', { type })
    },
  })
}

/**
 * 跳转到个人信息页面
 */
function toInfo() {
  uni.navigateTo({
    url: '/pages/mine/information',
  })
}

const commonFunctions = ref([
  {
    icon: '/static/images/1官方商城.png',
    title: '我的点评',
    url: '/pages/mine/myReview',
  },
  {
    icon: '/static/images/1官方商城.png',
    title: '意见反馈',
    url: '/pages/mine/feedback',
  },
  {
    icon: '/static/images/1官方商城.png',
    title: '优惠券',
    url: '/pages/mine/coupon',
  },
  {
    icon: '/static/images/1官方商城.png',
    title: '联系客服',
    url: '/pages/mine/contactKefu',
  },
  {
    icon: '/static/images/1官方商城.png',
    title: '邀请好友',
    handler: showQrcode,
  },
  {
    icon: '/static/images/1官方商城.png',
    title: '收货管理',
    url: '/pages/receiver/receiverManagement',
  },
  {
    icon: '/static/images/1官方商城.png',
    title: '购物车',
    url: '/pages/goods/shoppingCart',
  },
  {
    icon: '/static/images/1官方商城.png',
    title: '发票信息',
    url: '/pages/mine/invoice',
  },
])

// 常用功能跳转
function goPage(item) {
  if (item.handler) {
    item.handler()
    return
  }

  const url = item.url
  if (url === '/pages/goods/shoppingCart') {
    // 当 url 为 tabbar 页面时，使用 uni.switchTab 跳转
    uni.switchTab({
      url,
      fail: (err) => {
        console.error('跳转失败', err)
      },
    })
  }
  else if (url) {
    // 其他有效 url 使用 uni.navigateTo 跳转
    uni.navigateTo({
      url,
      fail: (err) => {
        console.error('跳转失败', err)
      },
    })
  }
}

// 一键登录功能
async function handleLogin() {
  const result = await userStore.wxLogin()
  console.log('LOGIN', result)
}

// 登录提示框状态定义
const show = ref(false)

// 显示页面时检查登录状态
onShow(() => {
  // 现在可以正常调用hasLoginInfo()判断登录状态
  if (!userStore.hasLoginInfo()) {
    uni.showToast({
      title: '您还未登录',
      icon: 'none',
    })
    // show.value = true
  }
  else {
    // 已登录时
    show.value = false
  }
})

const notice = ref(`感谢您对拈花湾景区的信赖和支持！
为更好的保护您的个人信息安全，请务必仔细阅读并充分理解我们更新的《拈花湾文旅用户服务协议》《拈花湾旅游服务用户服务协议》。
我们将严格按照其中各项条款使用和保护您的个人信息。详细信息请阅读最新版《拈花湾文旅用户服务协议》《拈花湾旅游服务用户服务协议》。`)

// 跳转登录页面
function goLogin() {
  uni.navigateTo({
    url: '/pages/login/login',
  })
}

// 添加小程序码相关变量
const showQrcodeModal = ref(false)
const qrcodePath = ref('')
const qrcodeLoading = ref(false)

// 获取并显示小程序码
async function showQrcode() {
  if (qrcodeLoading.value)
    return
  qrcodeLoading.value = true

  try {
    uni.showLoading({ title: '生成中...' })

    // 调用API获取小程序码，传入首页参数
    const response = await getSun({
      params: {
        page: 'pages/index/index', // 首页路径
      },
    })

    // 获取返回的数据（假设是base64字符串）
    const imageBase64 = (response.data as unknown) as string

    if (!imageBase64) {
      throw new Error('未获取到小程序码')
    }

    // 处理base64数据
    if (imageBase64.startsWith('data:image')) {
      // 如果是完整的data URL格式，需要提取base64部分
      const base64Data = imageBase64.split(',')[1]
      showQrcodeInModal(base64Data)
    }
    else {
      // 如果只是纯base64字符串
      showQrcodeInModal(imageBase64)
    }
  }
  catch (error) {
    console.error('生成小程序码失败:', error)
    uni.showToast({ title: '生成失败', icon: 'error' })
  }
  finally {
    uni.hideLoading()
    qrcodeLoading.value = false
  }
}

// 在模态框中显示小程序码
function showQrcodeInModal(base64Data) {
  // 为小程序码创建专用临时文件路径
  const filePath = `${(uni as any).env.USER_DATA_PATH}/index_qrcode_temp.png`

  // 将base64转为临时文件
  const fs = uni.getFileSystemManager()
  fs.writeFile({
    filePath,
    data: uni.base64ToArrayBuffer(base64Data),
    encoding: 'binary',
    success: () => {
      // 设置小程序码路径并显示模态框
      qrcodePath.value = filePath
      showQrcodeModal.value = true
    },
    fail: (err) => {
      console.error('写入文件失败:', err)
      uni.showToast({ title: '生成失败', icon: 'error' })
    },
  })
}

// 保存小程序码到相册
function saveQrcodeToAlbum() {
  saveImageToAlbum(qrcodePath.value, '小程序码已保存到相册')
}

// 关闭小程序码模态框
function closeQrcodeModal() {
  showQrcodeModal.value = false
}

// 通用的保存图片到相册函数
function saveImageToAlbum(filePath, successMsg = '图片已保存到相册') {
  if (!filePath) {
    uni.showToast({ title: '没有可保存的图片', icon: 'none' })
    return
  }

  // 获取保存到相册的权限
  uni.authorize({
    scope: 'scope.writePhotosAlbum',
    success() {
      // 已获得授权，保存图片
      uni.saveImageToPhotosAlbum({
        filePath,
        success: () => {
          uni.showToast({ title: successMsg, icon: 'none' })
        },
        fail: (err) => {
          console.error('保存失败:', err)
          if (err.errMsg.includes('auth deny')) {
            uni.showModal({
              title: '提示',
              content: '需要您授权保存图片到相册',
              confirmText: '去授权',
              success: (res) => {
                if (res.confirm) {
                  // 打开设置页面让用户手动授权
                  uni.openSetting({
                    success: (settingRes) => {
                      console.log('设置页面返回：', settingRes)
                    },
                  })
                }
              },
            })
          }
          else {
            uni.showToast({ title: '保存失败', icon: 'none' })
          }
        },
      })
    },
    fail() {
      // 用户拒绝授权或首次使用
      uni.showModal({
        title: '提示',
        content: '需要您授权保存图片到相册',
        confirmText: '去授权',
        success: (res) => {
          if (res.confirm) {
            uni.openSetting()
          }
        },
      })
    },
  })
}
</script>

<template>
  <image :style="{ marginTop: `${safeAreaInsets?.top}px` }" class="fixed top-0 z-[-1] h-100vh w-100vw" src="/static/images/mineBack.png" mode="scaleToFill" />
  <view class="box-border min-h-[100vh] overflow-hidden">
    <!-- 顶部信息栏 -->
    <view
      :style="{ marginTop: `${safeAreaInsets?.top}px` }"
      class="min-h-[28vh]"
    >
      <view class="h-[10vh]" />
      <view class="flex items-center justify-between p5">
        <view class="flex items-center justify-center">
          <image class="h-20 w-20 rounded-full" style="border: 6rpx solid #fff" :src="userInfo.avatarUrl" mode="aspectFill" @click="toInfo" />
          <view class="ml-5 text-xl font-600">
            {{ userInfo.nickName }}
          </view>
        </view>
        <view>
          <wd-icon name="setting" color="" size="20px" @click="toInfo" />
        </view>
      </view>
    </view>
    <!-- 日历活动 -->
    <CalendarActivity
      :is-scroll="false"
    />
    <!-- 功能区 -->
    <view>
      <wd-card>
        <view class="box-border flex justify-evenly gap-5 py-5 text-black font-500">
          <view @click="toOrderList('待使用')">
            <image class="h-16 w-16" src="/static/images/grid-icon01.png" mode="aspectFill" />
            <view class="text-center">
              待使用
            </view>
          </view>
          <view @click="toOrderList('待付款')">
            <image class="h-16 w-16" src="/static/images/grid-icon01.png" mode="aspectFill" />
            <view class="text-center">
              待付款
            </view>
          </view>
          <view @click="toOrderList('已完成')">
            <image class="h-16 w-16" src="/static/images/grid-icon01.png" mode="aspectFill" />
            <view class="text-center">
              已完成
            </view>
          </view>
          <view @click="toOrderList('全部订单')">
            <image class="h-16 w-16" src="/static/images/grid-icon01.png" mode="aspectFill" />
            <view class="text-center">
              全部订单
            </view>
          </view>
        </view>
      </wd-card>
      <view class="h-3" />
      <wd-card>
        <view class="pt-3 text-lg text-gray-800">
          常用功能
        </view>
        <view class="grid grid-cols-4 box-border gap-5 py-3 text-black font-500">
          <view v-for="(item, index) in commonFunctions" :key="index" @click="goPage(item)">
            <image class="h-16 w-16" :src="item.icon" mode="aspectFill" />
            <view class="text-center">
              {{ item.title }}
            </view>
          </view>
        </view>
      </wd-card>
    </view>
  </view>
  <wd-popup v-model="show" custom-style="border-radius:32rpx;" :close-on-click-modal="false" :safe-area-inset-bottom="true">
    <image class="h-32 w-full" src="https://m.360buyimg.com/i/jfs/t1/306136/5/15674/110093/686777b2F2aac0155/a1b9c1b5ef5807c1.jpg" mode="aspectFill" />
    <view class="mt-5 w-[500rpx] flex flex-col items-center justify-center rounded-[32rpx] px-5">
      <view class="text-36rpx">
        协议更新提示
      </view>
      <view class="scrollbar-hide mt-4 h-[320rpx] overflow-y-auto whitespace-pre-line">
        {{ notice }}
      </view>
      <view
        class="mt-7 h-80rpx w-70% flex items-center justify-center rounded-3xl bg-[linear-gradient(to_right,#e0cebd,#bfa189)] text-white"
        @click="goLogin"
      >
        阅读并同意
      </view>
      <view
        class="mt-1 h-80rpx w-70% flex items-center justify-center rounded-3xl text-gray"
      >
        不同意
      </view>
    </view>
  </wd-popup>
  <!-- <wd-button type="primary" size="small" @click="handleLogin">
    微信一键登录
  </wd-button> -->

  <!-- 添加小程序码模态框 -->
  <wd-popup
    v-model="showQrcodeModal"
    position="center"
    custom-style="width: 80%; border-radius: 16rpx; background-color: transparent;"
    @close="closeQrcodeModal"
  >
    <view class="flex flex-col items-center rounded-lg bg-white p-4">
      <view class="mb-4 text-center text-36rpx font-bold">
        邀请好友
      </view>
      <image
        v-if="qrcodePath"
        :src="qrcodePath"
        class="mb-4 h-500rpx w-500rpx"
        mode="aspectFit"
        @longpress="saveQrcodeToAlbum"
      />
      <view class="mb-4 text-center text-28rpx text-gray-600">
        长按图片可保存到相册
      </view>
    </view>
  </wd-popup>
</template>

<style lang="scss" scoped>

</style>
